package common.httpclient;


import com.google.gson.Gson;
import common.helper.LogHelper;
import common.utils.HttpUtils;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Objects;
import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AppApiHttpClient {

  public AppApiHttpClient(HttpApiClient apiClient, Gson gson) {
    this.apiClient = apiClient;
    this.gson = gson;
  }

  private final Logger logger = LoggerFactory.getLogger("rpc");

  private HttpApiClient apiClient;

  private Gson gson;

  public <T> T getRespObject(String url, Map<String, String> uriVariables, Class<T> respBean,
      String httpMethod) {
    String responseStr = getRespObject(url, uriVariables, httpMethod);
    return gson.fromJson(responseStr, respBean);
  }

  private String getRespObject(String url, Map<String, String> uriVariables, String httpMethod) {
    String responseStr = "";
    Long now = System.currentTimeMillis();
    try {
      if (Objects.equals(HttpGet.METHOD_NAME, httpMethod)) {
        responseStr = apiClient.get(url, uriVariables);
      } else {
        responseStr = apiClient.post(url, uriVariables);
      }
    } catch (Exception e) {
      logger.error("http error", e);
    } finally {
      Long cost = System.currentTimeMillis() - now;
      String logStr = LogHelper
          .getLogString(url, HttpUtils.getStringByMap(uriVariables), responseStr, cost);
      logger.info(logStr);
    }
    return responseStr;
  }

  public <T> T getRespObject(String url, Map<String, String> uriVariables, Type type,
      String httpMethod) {
    String responseStr = getRespObject(url, uriVariables, httpMethod);
    return gson.fromJson(responseStr, type);
  }
}
